"""
    @author yu_chen
    @date  
    @todo 
"""
import datetime

import requests
import json
from retrying import retry


class Proxy:

    def __init__(self):
        self.index = 0
        self.data = []
        self.get_proxy_list()

    @retry(stop_max_attempt_number=3)
    def get_proxy_list(self):
        url = "http://webapi.http.zhimacangku.com/getip?num=5&type=2&pro=&city=0&yys=0" \
              "&port=1&time=1&ts=1&ys=0&cs=0&lb=1&sb=0&pb=45&mr=2&regions="
        print(url)
        response = requests.get(url)
        response_str = response.content.decode()
        result = json.loads(response_str)
        self.data = result['data']
        print(self.data)

    def check_and_get_proxy_ip(self):
        """
        检查并获取可用的代理IP
        :return: https://ip:端口
        """
        if self.index > len(self.data) - 1:
            # 重新获取IP池
            self.get_proxy_list()
            self.index = 0
        else:
            self.index += 1

    @retry(stop_max_attempt_number=3)
    def get_proxy_url(self):
        """
        失败重试
        获得代理的URL
        :return:
        """
        data_now_str = datetime.datetime.now().__format__('%Y-%m-%d %H:%M:%S')
        if self.index > len(self.data) - 1 or self.data[self.index]['expire_time'] < data_now_str:
            self.check_and_get_proxy_ip()

        current_url = "http://%s:%s" % (self.data[self.index]['ip'], self.data[self.index]['port'])

        print("当前URL:%s\t过期时间:%s" % (current_url, self.data[self.index]['expire_time']))
        return current_url


if __name__ == '__main__':
    proxy = Proxy()
    for i in range(10):
        print(proxy.get_proxy_url())
